package com.hxzy.controller.login;

import com.hxzy.common.enums.AckCode;
import com.hxzy.common.resp.R;
import com.hxzy.config.security.AdminLoginResp;
import com.hxzy.config.security.TokenService;
import com.hxzy.controller.login.req.AdminLoginReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @Author wy
 * @Description TODO
 * @Date 2023/9/27 10:08
 * @Version 1.0
 */
@RestController
@RequestMapping(value = "/api")
public class LoginController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenService  tokenService;

    @PostMapping(value = "/login")
    public R  login(@RequestBody @Valid AdminLoginReq req){
        //构建一个登录对象
        UsernamePasswordAuthenticationToken  token=new UsernamePasswordAuthenticationToken(req.getAccount(),req.getPassword());
        //如果没有报错，说明认证成功了
        Authentication authenticate = this.authenticationManager.authenticate(token);

        //如果认证成功
        if(authenticate.isAuthenticated()){
           //换令牌
            AdminLoginResp  adminLoginResp= (AdminLoginResp) authenticate.getPrincipal();
            String jwtToken = this.tokenService.createJwtToken(adminLoginResp);
            return R.okHasData(jwtToken);
        }else{
            return R.build(AckCode.USER_ACCOUNT_AUTH_EXCEPTION);
        }
    }

}
